package jgo.plugins;

import jgo.JGo;
import jgo.Plugin;
import jgo.core.MiddlewarePlugin;
import jgo.Context;
import jgo.Handler;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.nio.file.Files;

public class StaticFilePlugin extends MiddlewarePlugin {
    private String directory;
    private String prefix;

    public StaticFilePlugin(String directory, String prefix) {
        this.directory = directory;
        this.prefix = prefix.endsWith("/") ? prefix : prefix + "/";
    }

    @Override
    public void init(JGo jgo) {
        jgo.logger.info("Initializing StaticFilePlugin with directory: {} and prefix: {}", directory, prefix);
        // 在这里可以添加一些初始化逻辑，比如检查目录是否存在
    }

    @Override
    public void handle(Context ctx, Handler next) {
        String path = ctx.getPath();
        if (path.startsWith(prefix)) {
            String remainingPath = path.substring(prefix.length());
            Path filePath = Paths.get(directory, remainingPath);
            if (!Files.exists(filePath) || Files.isDirectory(filePath)) {
                next.handle(ctx); // 如果文件不存在或是目录，继续下一个处理器
            } else {
                // 处理静态文件的逻辑
                try {
                    String mimeType = Files.probeContentType(filePath);
                    ctx.contentType(mimeType != null ? mimeType : "application/octet-stream")
                       .body(Files.readAllBytes(filePath));
                    ctx.setHandled(true);
                } catch (IOException e) {
                    ctx.status(500).string("Error serving static file");
                }
            }
        } else {
            next.handle(ctx); // 如果路径不匹配前缀，继续下一个处理器
        }
    }
}